package com.tjn.synchronized_;

/**
 * @author 陶镓妮
 * @version 1.0
 */
public class DeadLock {
    public static void main(String[] args) {
        //模拟一个死锁
        DeadLockDemo A = new DeadLockDemo(true);
        A.setName("A线程");
        DeadLockDemo B = new DeadLockDemo(false);
        B.setName("B线程");
        A.start();
        B.start();
    }
}

class DeadLockDemo extends Thread{
    static Object o1 = new Object();
    static Object o2 = new Object();
    boolean flag;

    public DeadLockDemo(boolean flag) {
        this.flag = flag;
    }

    //如果flag为true，线程A会先获取o1,,然后去尝试获取o2,
    //如果flag为false，线程B会先获取o2,然后去尝试获取o1,
    //这时o1和o2都各自被线程A和线程B占用着,
    //线程A和线程B都在等待对方释放资源,
    //这就形成了死锁
    @Override
    public void run() {
        if(flag){
            synchronized(o1){
                System.out.println(Thread.currentThread().getName() + "进入1");
                synchronized(o2){
                    System.out.println(Thread.currentThread().getName() + "进入2");
                }
            }
        }else{
            synchronized(o2){
                System.out.println(Thread.currentThread().getName() + "进入3");
                synchronized(o1){
                    System.out.println(Thread.currentThread().getName() + "进入4");
                }
            }
        }
    }
}